package com.jinli.security.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jinli.security.auth.model.ExpUserDetails;
import com.jinli.security.auth.model.User;
import com.jinli.security.auth.service.IUserService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author zhangxj
 * @date 2024/12/25
 * @Description
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, username));
        if (Objects.isNull(user)) {
            log.error("Query returned no results for user '{}'", username);
            throw new UsernameNotFoundException(StrUtil.format("Username '{}' not found", username));
        } else {
            // 设置权限集合，后续需要数据库查询
            List<GrantedAuthority> authoryList = AuthorityUtils.createAuthorityList("admin");
            return new ExpUserDetails(user.getUserName(), user.getPhone(), user.getPassword(),
                    true, true, true, true, authoryList);
        }
    }
}
